﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace ip地址相关类
{
    class Program
    {
        static void Main(string[] args)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("万胜杰 开始 获取 WWW.CCTV.COM 的所有的IP地址：");
            try
            {
                IPAddress[] ips = Dns.GetHostAddresses("www.cctv.com");
                foreach (IPAddress item in ips)
                {
                    sb.AppendLine(item.ToString());
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message + "获取失败！！");
            }

            string hostName = Dns.GetHostName();
            sb.AppendLine("开始获取本机所有 Ip地址:");
            IPHostEntry me = Dns.GetHostEntry(hostName);
            foreach (IPAddress ip in me.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    sb.AppendLine("ipv4 : " + ip.ToString());
                }
                else if (ip.AddressFamily == AddressFamily.InterNetworkV6)
                {
                    sb.AppendLine("ipv6 : " + ip.ToString());
                }
                else
                {
                    sb.AppendLine("其他 : " + ip.ToString());
                }
            }

            IPAddress localip = IPAddress.Parse("::1");
            Output(sb, localip);
            IPAddress localip1 = IPAddress.Parse("127.0.0.1");
            Output(sb, localip1);
            Console.WriteLine(sb);

            Console.ReadKey();
        }

        private static void Output(StringBuilder sb, IPAddress localip)
        {
            IPEndPoint iep = new IPEndPoint(localip, 80);
            if (localip.AddressFamily == AddressFamily.InterNetworkV6)
            {
                sb.Append("IPV6 端点：" + iep.ToString());
            }
            else
            {
                sb.Append("IPV4 端点：" + iep.ToString());
            }

            sb.Append(",端口：" + iep.Port);
            sb.Append(" ，地址：" + iep.Address);
            sb.Append("， 地址族 ：" + iep.AddressFamily);

            Console.ReadKey();
        }
    }
}
